using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using BabyPoetryConference.IoC;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog;

namespace BabyPoetryConference.WebAPI
{
    public class Startup
    {
        private static readonly ILogger _Logger = LogManager.GetCurrentClassLogger();
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            _Logger.Info("Startup ConfigureServices...");
            services.AddHostedService<GlobalHostService>();
            services.AddControllers();
            services.AddControllersWithViews().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            });
            _Logger.Info("Startup ConfigureServices finished.");
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            _Logger.Info("Startup IApplicationBuilder...");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            _Logger.Info("Startup IApplicationBuilder finished.");
        }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            _Logger.Info($"Startup ConfigureContainer Autofac...");
            builder.Register(cc =>
            {
                //将配置添加到ConfigurationBuilder
                var config = new ConfigurationBuilder();
                //config.AddJsonFile来自Microsoft.Extensions.Configuration.Json
                //config.AddXmlFile来自Microsoft.Extensions.Configuration.Xml
                config.AddIniFile("cfg.ini");
                IConfiguration cfg = config.Build();
                return cfg;
            });

            var ms = new Module[]
            {
                new LogicModule()
            };
            IoCManager.Instance.Register(builder, ms);
            _Logger.Info($"Startup ConfigureContainer Autofac finished.");
        }
    }
}
